#!/usr/bin/env node

const koa = require("koa"),
  bodyparser = require("koa-bodyparser"),
  tasks = require("./routes/tasks.js"),
  user = require("./routes/user.js"),
  video = require("./routes/video.js"),
  animation = require("./routes/animation"),
  json = require("koa-json"),
  logger = require("koa-logger"),
  jwt = require("koa-jwt"),
  jwt2 = require("jsonwebtoken"),
  cors = require("koa2-cors"),
  { koaBody } = require("koa-body"),
  { JWT_KEY } = require("./lib/constant.js"),
  app = new koa({
    debug: true,
    http: true,
    key: "/usr/local/cert/www.h5weixin.club.key",
    cert: "/usr/local/cert/www.h5weixin.club.crt",
  });

app.use(json());
app.use(logger());
app.use(
  cors({
    "Access-Control-Allow-Origin": "*",
  })
);
app.use(
  koaBody({
    multipart: true,
    strict: false,
  })
);
app.use(jwt({ secret: JWT_KEY }).unless({ path: /\/api\/users\/login$/ }));
app.use(bodyparser({ enableTypes: ["json", "form", "text"] }));
app.use(async (ctx, next) => {
  let token = ctx.header.authorization;
  if (typeof token !== "undefined") {
    token = token.split(" ")[1];
    let user = jwt2.verify(token, JWT_KEY);
    ctx.userId = user.id;
  }

  await next();
});
app.use(tasks.routes());
app.use(user.routes());
app.use(video.routes());
app.use(animation.routes());
app.listen(8080);
